package com.example.demo2userdetailsservice.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager users = new InMemoryUserDetailsManager();
        users.createUser(User.withUsername("user").password("{noop}123456").roles("user").build());
//        users.createUser(User.withUsername("admin").password("{noop}123456").roles("admin").build());
        return users;
    }
    @Bean("userDetailsService2")
    UserDetailsService userDetailsService2() {
        InMemoryUserDetailsManager users = new InMemoryUserDetailsManager();
//        users.createUser(User.withUsername("user").password("{noop}123456").roles("user").build());
        users.createUser(User.withUsername("admin").password("{noop}123456").roles("admin").build());
        return users;
    }

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // login放行，其他请求验证
        http.authorizeHttpRequests(authorize->authorize.requestMatchers("login").permitAll().anyRequest().authenticated());

//        http.formLogin(Customizer.withDefaults());
        /**
         * 指定使用的userDetailsService2
         * 如果不指定默认使用userDetailsService
         */
        http.userDetailsService(userDetailsService2());
        http.formLogin(form->form.successForwardUrl("/success"));// successForwardUrl 跳转方式是post
        http.csrf(csrf->csrf.disable());
        return http.build();

    }
}
